extends Node2D

const Transiton := preload("res://Scenes/UI/TransitionScene.tscn")

const STAGE_PATH := "res://Scenes/Stage/"
const STAGE_NAME := "stage"

signal stage_end


var _stage_array: = []

var _stage_cache: = {}

var current_stage: BaseStage = null
var new_stage:BaseStage = null
var current_stage_name: String = ""

var _is_transitioning: = false
@export_group("debug")
@export var debug:bool
@export var debug_stage_name: String



func _ready() -> void :
	await get_parent().ready
	GameEvents.player_died.connect(relode_current_stage)
	_preload_stages()
	if !debug:
		if Global.current_stage_name != "":
			change_stage(Global.current_stage_name)
		else:
			change_stage("stage1")
	else:
		change_stage(debug_stage_name)
	stage_end.connect(func():
		Global.player.freeze()
		next_stage()
		)


func _preload_stages() -> void :
	# 使用 ResourceLoader 逐个尝试加载按序号命名的场景（stage1, stage2, ...）
	# 这样在导出后也能可靠地找到资源路径（避免部分平台上 DirAccess 无法列出导出资源的问题）
	var idx: int = 1
	while true:
		var file_name = STAGE_NAME + str(idx) + ".tscn"
		var stage_path = STAGE_PATH + file_name
		# 如果资源不存在则认为序列结束
		if not ResourceLoader.exists(stage_path):
			break
		_stage_array.append(stage_path)
		var stage_name = file_name.get_basename()
		_stage_cache[stage_name] = stage_path
		idx += 1



func change_stage(stage_name: String) -> void :
	if _is_transitioning:
		return

	_is_transitioning = true
	#MusicPlayer.play_sfx("ChangeScene")
	
	
	var old_stage_name = Global.current_stage_name
	var stage_path = _stage_cache.get(stage_name)
	if not stage_path:
		push_error("Stage not found: " + stage_name)
		_is_transitioning = false
		return
	current_stage_name = stage_name
	var transition :Transition= Transiton.instantiate()
	transition.next_scene_path = stage_path
	transition.is_stage_transition = true
	transition.transition_end.connect(func(stage): new_stage = stage.instantiate())
	Global.main.transition_parent.add_child(transition)
	await transition.transition_end
	if current_stage:
		current_stage.queue_free()
		await current_stage.tree_exited
	Global.main.current_npc = new_stage.current_npc
	
	
	DialogHandler.current_stage = new_stage
	if old_stage_name != stage_name:
		GameEvents.stage_changed.emit()
	Global.current_stage_name = stage_name
	add_child(new_stage)
	current_stage = new_stage

		
	
	





	
	_is_transitioning = false

func relode_current_stage() -> void:
	change_stage(current_stage_name)
	await GameEvents.stage_entered
	SaveManager.load_stage()

func next_stage() -> void :
	if not Global.current_stage_name:
		change_stage(STAGE_NAME + "1")
		return

	var current_number = int(Global.current_stage_name.trim_prefix(STAGE_NAME))
	var _next_stage = STAGE_NAME + str(current_number + 1)

	if _stage_cache.has(_next_stage):
		change_stage(_next_stage)
	else:
		printerr("Stage not Found", _next_stage)

func _input(event: InputEvent) -> void:
	if event.is_action_pressed("relode"):
		relode_current_stage()
